package co.znmc.test.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @Author: chenbin
 * @Description:
 * @Date: create in 2021/11/5 16:48
 */
@Configuration
@MapperScan("co.znmc")
@EnableTransactionManagement
public class MybatisConfig {
  private DataSource dataSource;

  @Bean
  public DataSource dataSource() {
    if (dataSource != null) {
      return dataSource;
    }
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setDriverClassName("com.mysql.cj.jdbc.Driver");
    hikariConfig.setJdbcUrl("jdbc:mysql://10.0.8.227:3306/znmc_2021_09_06?useSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8");
    hikariConfig.setUsername("znmc");
    hikariConfig.setPassword("xjr@znmc");
    hikariConfig.setMinimumIdle(1);
    hikariConfig.setMaximumPoolSize(1);
    hikariConfig.setConnectionTimeout(1000);
    HikariDataSource hikariDataSource = new HikariDataSource(hikariConfig);
    this.dataSource = hikariDataSource;
    return hikariDataSource;
  }

  @Bean
  public SqlSessionFactory sqlSessionFactory() throws Exception {
    SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
    factoryBean.setDataSource(dataSource());
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    factoryBean.setMapperLocations(resolver.getResources("classpath*:co/znmc/**/dao/impl/*.xml"));
    SqlSessionFactory sqlSessionFactory = factoryBean.getObject();
    sqlSessionFactory.getConfiguration().setLogImpl(StdOutImpl.class);
    return sqlSessionFactory;
  }

  @Bean(name = "transactionManager")
  public PlatformTransactionManager annotationDrivenTransactionManager() {
    DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
    //设置事务管理器管理的数据源
    transactionManager.setDataSource(dataSource());
    return transactionManager;
  }
}
